from .models import DBSession, MyModel
from IndexedVector import IndexedVector
from IndexedVectorList import IndexedVectorList
from PeriodicReturns import PeriodicReturns
from PeriodicReturnsList import PeriodicReturnsList
from RandomizedList import RandomizedList
from Simulation import Simulation
from SimulationList import SimulationList
from Stock import Stock
from StockList import StockList
from fetchPortfolio import GoogleQuote
from pyramid.response import Response
from pyramid.view import view_config
from sqlalchemy.exc import DBAPIError
import CalculateValueAtRisk
from Start import *
import percentile
import __init__
import os
import sys
from pyramid.httpexceptions import HTTPFound



@view_config(route_name='chartvar', renderer='templates/chartvar.pt')
def chartvar(request, permission='view'):
    erg = []
    for summe in SimulationList.summe:
        erg.append(summe)
    perc = percentile.percentile(erg, 5)
    return {'erg': erg, 'percentile':perc, 'length': len(erg)}
        
@view_config(route_name='chart', renderer='templates/chart.pt')
def chart(request, permission='view'):
    # return HTTPFound(location=request.route_url('chart',
    #                                             pagename='Chart'))
    count = 0
    future = 0
    startdate = ''
    enddate = ''
    pwd = os.getcwd() + "/fin2012/static/data.csv"
    try:
        os.remove(pwd)
    except:
        pass
    try:
        deleteObjects()
    except:
        pass
    if __init__.symbols and __init__.settings:
        start = Start(__init__.symbols)
        count, future, startdate, enddate = __init__.settings
        #start.generateData(int(a['count']), int(a['future']), a['startdate'], a['enddate'])
        start.generateData(int(count),int(future),startdate,enddate)
    else:
        symbols = ['MSFT', 'YHOO']
        start = Start(symbols)
        start.generateData()
        __init__.help = 1
    '''
    symbols = DBSession.query(Keys).all()
    symbolList = []
    for s in symbols:
        symbolList.append(s.key)
        
    start_date = '2012-01-01'
    end_date = datetime.date.today().isoformat()
    #g = GoogleQuote().getData(symbolList, start_date, end_date)'''
    settings = {'count':count,'future':future,'startdate':startdate,'enddate':enddate}
    return settings
    
    

@view_config(route_name='getUserInput', renderer='')
def getUserInput(request):
    symbols = request.POST['symbols']
    count = request.POST['count']
    future = request.POST['future']
    startdate = request.POST['startdate']
    enddate = request.POST['enddate']
    pwd = os.getcwd() + "/fin2012/static/data.csv"
    try:
        os.remove(pwd)
    except:
        pass
   
    deleteObjects()
    __init__.symbols = []
    for s in symbols.split(','):
        __init__.symbols.append(str(s))
    
    # self, count=10, future=8, startdate='2012-01-01', enddate=datetime.date.today().isoformat(), start=0, end=10
    #start = Start(__init__.symbols)
    #start.generateData(int(count), int(future), startdate, enddate)
    
    
    __init__.settings = [count, future, startdate, enddate]
    chart(request,'view')
    url = request.route_url('chart') 
    return HTTPFound(location=url)

def deleteObjects():
    for index in IndexedVectorList.iVectorList:
        del index
    for index in PeriodicReturnsList.returnsList:
        del index
    for index in RandomizedList.rList:
        del index
    for index in StockList.stockList:
        del index
    IndexedVectorList.iVectorList = []
    PeriodicReturnsList.returnsList = []
    RandomizedList.rList = []
    StockList.stockList = []
    SimulationList.simList = []
    SimulationList.summe = []
    
@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
    try:
        one = DBSession.query(MyModel).filter(MyModel.name == 'one').first()
    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    return {'one': one, 'project': 'FIN2012'}

conn_err_msg = """\
Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to run the "initialize_FIN2012_db" script
    to initialize your database tables.  Check your virtual 
    environment's "bin" directory for this script and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.

After you fix the problem, please restart the Pyramid application to
try it again.
"""

